package cn.fenqing.juc.thread;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author fenqing
 * @version 0.0.1
 * @date 2021/7/19 14:00
 * @description 线程不安全
 */
public class ThreadUnsafetyDemo {

    public static void main(String[] args) throws InterruptedException {

        int threadSize = 1000;
        ThreadUnsafety threadUnsafety = new ThreadUnsafety();
        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(threadSize);

        //开辟1000个线程,每个线程进行添加
        for (int i = 0; i < threadSize; i++) {
            executorService.execute(() -> {
                threadUnsafety.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(threadUnsafety.getNum());

    }


}

@Getter
class ThreadUnsafety {
    /**
     * 数字
     */
    private int num = 0;

    /**
     * 自增
     */
    public void add(){
        this.num++;
    }
}
